package cn.edu.cqut.mdm.web;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.cqut.mdm.container.NetworkPublishedModuleContainer;
import cn.edu.cqut.mdm.core.dispatcher.LocalDispatcher;
import cn.edu.cqut.mdm.core.message.RequestMessage;
import cn.edu.cqut.mdm.core.message.ResponseMessage;
import cn.edu.cqut.mdm.core.module.RemoteMethod;

@Controller
@RequestMapping("/")
public class JsonController {
	@RequestMapping("/json")
	@ResponseBody
	public String json(String json) {
		Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
		classMap.put("method", RemoteMethod.class);
		JsonConfig config = new JsonConfig();
		config.setClassMap(classMap);
		config.setRootClass(RequestMessage.class);
		config.setIgnoreTransientFields(true);
		config.setExcludes(new String[]{"parameterTypes", "returnType"});
		RequestMessage requestMessage = (RequestMessage) JSONSerializer.toJava(JSONObject.fromObject(json, config), config);
		ResponseMessage responseMessage = null;
		if(NetworkPublishedModuleContainer.getInstance().getModule(requestMessage.getRemoteModuleUid()) == null) {
			responseMessage = new ResponseMessage();
			responseMessage.setStatus(1);
		} else {
			responseMessage = LocalDispatcher.getLocalDispatcher().dispatch(requestMessage);
		}
		String result = null;
		if(responseMessage != null){
			result = JSONObject.fromObject(responseMessage).toString();
		}
		return result;
	}
}